package com.bitBusy.manageyourriches.activity;

import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.GridView;

import com.appRating.RateApp;
import com.bitBusy.manageyourriches.R;
import com.bitBusy.manageyourriches.database.managers.DatabaseInteractor;
import com.bitBusy.manageyourriches.licenseagreement.EULA;
import com.bitBusy.manageyourriches.utilityClasses.adapters.ImageButtonAdapterGridView;
import com.bitBusy.manageyourriches.utilityClasses.dialogboxes.DialogBoxPrompts;
import com.bitBusy.manageyourriches.utilityClasses.display.DisplayInputTextUsers;
import com.bitBusy.manageyourriches.utilityClasses.display.DisplayMessages;
import com.bitBusy.manageyourriches.utilityClasses.navigation.ActionBarChoice;
import com.bitBusy.manageyourriches.utilityClasses.setters.AddAddNewToMap;

public class HomeActivity extends Activity implements DisplayInputTextUsers {

	/** Key for amount chosen, in the intent object used to start the next activity (ConfirmActivity)*/
    public final static String AMOUNT_CHOSEN = "com.bitBusy.manageMyRiches.AMOUNT"; 

    /** Key for SpendingCategory name chosen, in the intent object used to start the next activity (ConfirmActivity)*/
    public final static String CATEGORY_CHOSEN = "com.bitBusy.manageMyRiches.CATEGORY";
    
    /** Key for SpendingCategory image chosen, in the intent object used to start the next activity (ConfirmActivity)*/
    public final static String CATEGORY_IMAGE_CHOSEN = "com.bitBusy.manageMyRiches.CATEGORYIMAGE";
    
    /**Default image for add new category*/
    public final static int CATEGORYADDNEWIMG  = R.drawable.add_new;

    private static final String DELETETITLE = "Delete category";
    
    private static final String DELETEMESSAGE = "Delete category: ";
    
    
	private static Context myAlarmsContext;
   
     
    /**Database interactor object for this activity*/
	private DatabaseInteractor myDBInteractor;
	

	//Grid to hold image buttons
	GridView gridView;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	   RateApp.app_launched(this);
	   // RateApp.showRateDialog(this, null);
		myAlarmsContext = getApplicationContext();
	    	setContentView(R.layout.activity_home);
			myDBInteractor = new DatabaseInteractor(this);
			new EULA(this).show();
	    	setGridView();
	    	
	}	
	
	/**Method to set grid view*/
	private void setGridView()
	{
    	GridView gridview = (GridView) findViewById(R.id.gridview);
    	//set db instance context
		final ImageButtonAdapterGridView imgButtonAdapterObj = 
	    		new ImageButtonAdapterGridView(this, AddAddNewToMap.getModifiedMap(myDBInteractor.getAllCategoriesAndImages(),
	    										CATEGORYADDNEWIMG));
	    gridview.setAdapter(imgButtonAdapterObj);
	     gridview.setOnItemClickListener(new OnItemClickListener() {
	        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        	Map<String, Integer> categoryChosenMap = imgButtonAdapterObj.getItem(position);
        	if (categoryChosenMap != null)
        	{
        		String categoryChosen = categoryChosenMap.keySet().toArray(new String[categoryChosenMap.keySet().size()])[0];
        		int categoryPicID = categoryChosenMap.get(categoryChosen);
	        	if(AddAddNewToMap.ADDNEW.equals(categoryChosen))
	        	{
	        		addNewCategory();
	        	}
	        	else
	        	{
		        	EditText editText = (EditText) findViewById(R.id.home_amtText);
		        	String amountString = editText.getText().toString();
		        	
		        	try
		        	{
		        		double amount = Double.parseDouble(amountString);
			        	processInput(amount, categoryChosen, categoryPicID);
	
		        	}
		        	catch(NumberFormatException exception)
		        	{
		        		DisplayMessages.displayUserError(HomeActivity.this, DialogBoxPrompts.AMOUNTNOTENTEREDPROMPT.getPrompt());
		        	}
        	
	        	}
        	} 
        }
    });
			gridview.setOnItemLongClickListener(new OnItemLongClickListener(){
				public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id){
					Map<String, Integer> categoryChosenMap = imgButtonAdapterObj.getItem(position);
		        	if (categoryChosenMap != null)
		        	{
		        		final String categoryChosen = categoryChosenMap.keySet().toArray(new String[categoryChosenMap.keySet().size()])[0];
		        		if (!AddAddNewToMap.ADDNEW.equals(categoryChosen))
		        		{
		        			DisplayMessages.displayStandardDialog(HomeActivity.this,
									DELETETITLE, DELETEMESSAGE.concat(categoryChosen).concat(DialogBoxPrompts.QUESTIONMARK.getPrompt()), 
									DialogBoxPrompts.DIALOGOKPROMPT.getPrompt(), 
									new DialogInterface.OnClickListener() {
				    					public void onClick(DialogInterface dialog,int id) {
				    					if (myDBInteractor.deleteCategory(categoryChosen))
				    					{
				    						setGridView();
				    					}
				    					}}
									, DialogBoxPrompts.DIALOGCANCELPROMPT.getPrompt(), 
									new DialogInterface.OnClickListener() {
		    					public void onClick(DialogInterface dialog,int id) {
		    						dialog.cancel();
		    					}
		    				});
						
		        		}
		        	}
						
					return true;
				}
			});
	}
	
	
	/** Method to add a new category onto the home screen*/
	private void addNewCategory()
	{
		 DisplayMessages.displayUserInputTextBoxAndGetInput
			 (HomeActivity.this, this, DialogBoxPrompts.DIALOGADDCATEGORY.getPrompt(), DialogBoxPrompts.DIALOGADDCATEGORYPROMPT.getPrompt(),
					DialogBoxPrompts.DIALOGOKPROMPT.getPrompt(),DialogBoxPrompts.DIALOGCANCELPROMPT.getPrompt());
		
	}
			
	
	
	
	
	/** Method to refresh the activity*/
/*	private void refresh()
	{
		Intent intent = getIntent();
		finish(); 
		startActivity(intent);
	}*/
	
	/** Method to process user input
	 * @param the_amount entered by the user
	 * @param the name of category selected from the grid view
	 */
	private void processInput(double the_amount, String the_categoryName, int the_categoryPicID)
	{
		if (the_categoryName != null && the_categoryName != "")
		{
			Intent intent = new Intent(this, ConfirmActivity.class);
			intent.putExtra(AMOUNT_CHOSEN, the_amount);
			intent.putExtra(CATEGORY_CHOSEN, the_categoryName);	
			intent.putExtra(CATEGORY_IMAGE_CHOSEN, the_categoryPicID);
			startActivity(intent);

		}
	}

	/* (non-Javadoc)
	 * @see com.bitBusy.manageyourriches.utilityClasses.display.DisplayInputTextUsers#getText()
	 */
	@Override
	public void getTextFromDialog(String the_categoryName) {
			if(the_categoryName != null && the_categoryName != "")
		{
			new DatabaseInteractor(this).addCategory(the_categoryName);
			setGridView();	
		}
		
		else
		{
    	    DisplayMessages.displayUserError(HomeActivity.this, DialogBoxPrompts.DIALOGNONAMEENTERED.getPrompt());
		}

		
	}

		
	 @Override
	  public boolean onCreateOptionsMenu(Menu the_menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.actionbar_menu, the_menu);
	    return true;
	  }
	 @Override
	  public boolean onOptionsItemSelected(MenuItem the_item) {
	    ActionBarChoice.choiceMade(this, the_item.getItemId());

	    return true;
	  }

	 public static Context getAppContext()
	 {
		 return myAlarmsContext;
	 }

	

}
